package by.epam.xslttask.command;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Templates;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by IntelliJ IDEA.
 * User: Darya_Hrishanovich
 * Date: 7/6/12
 * Time: 3:53 AM
 * To change this template use File | Settings | File Templates.
 */
public abstract class Command {
    private Map<String, Templates> mapTemplates;
    private String relPath;
    private PrintWriter out;
    private ReadWriteLock lock;

    public Command(String relPath) {
        if(mapTemplates == null) {
            mapTemplates = new HashMap();
        }
        this.relPath = relPath;
        if(lock == null) {
            lock = new ReentrantReadWriteLock(true);
        }
    }

    public Document stringToDom(String xmlSource)
            throws SAXException, ParserConfigurationException, IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(xmlSource);
    }

    public PrintWriter getOut() {
        return out;
    }

    public void setOut(PrintWriter out) {
        this.out = out;
    }

    public String getRelPath() {
        return relPath;
    }

    public void setRelPath(String relPath) {
        this.relPath = relPath;
    }

    public ReadWriteLock getLock() {
        return lock;
    }

    public void setLock(ReadWriteLock lock) {
        this.lock = lock;
    }

    abstract public Map<String, String> execute() throws IOException, ServletException;

    public Map<String, Templates> getMapTemplates() {
        return mapTemplates;
    }
    
    public void addTemplates(String key, Templates value) {
        mapTemplates.put(key, value);
    }
}
